<?php

namespace App\Repository;

use App\Entity\AdminUser;
use App\Enum\RedisKeyEnum;
use App\Service\Redis;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @method AdminUser|null find($id, $lockMode = null, $lockVersion = null)
 * @method AdminUser|null findOneBy(array $criteria, array $orderBy = null)
 * @method AdminUser[]    findAll()
 * @method AdminUser[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class AdminUserRepository extends ServiceEntityRepository implements PasswordUpgraderInterface {
    private $redis;

    public function __construct (ManagerRegistry $registry, Redis $redis) {
        parent::__construct($registry, AdminUser::class);
        $this->redis = $redis->redis;
    }

    /**
     * Used to upgrade (rehash) the user's password automatically over time.
     */
    public function upgradePassword (UserInterface $user, string $newEncodedPassword): void {
        if (!$user instanceof AdminUser) {
            throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', \get_class($user)));
        }

        $user->setPassword($newEncodedPassword);
        $this->_em->persist($user);
        $this->_em->flush();
    }

    public function findAllToArray () {
        $result = [];

        $redis_key = RedisKeyEnum::REDIS_ADMIN_USER_FIND_ALL_BY_ARRAY_KEY;
        $redis_admin_user_data = $this->redis->get($redis_key);
        if (is_null($redis_admin_user_data)) {
            $objs = $this->findAll();
            foreach ($objs as $obj) {
                $result[$obj->getId()] = $obj->getUsername();
            }
            $this->redis->setex($redis_key, 600, serialize($result));
        } else {
            $result = unserialize($redis_admin_user_data);
        }

        return $result;
    }

    /**
     * 获取头像地址
     * @param $id
     * @return string|null
     */
    public function getAvatar ($id) {
        $obj = $this->find($id);
        return is_object($obj) ? $obj->getAvatar() : '';
    }

    /**
     * 获取头像地址
     * @param $id
     * @return string|null
     */
    public function getAuthor ($id) {
        $result = '未知用户';
        $obj = $this->find($id);
        if (is_object($obj)) {
            if ($obj->getNickname() != '') {
                $result = $obj->getNickname();
            } else {
                $result = $obj->getUsername();
            }
        }
        return $result;
    }
}
